<?php

include_once( 'options.php' );
include_once( TOptions::serverAppLibFile( 'TFire.php' ) );
include_once( TOptions::serverAppLibFile( 'TRegion.php' ) );
include_once( TOptions::serverFile( 'db.php' ) );

$region = new TRegion();
$regions = $region->selectAllRecords( '**', 'code' );

//echo '<pre>';
//var_dump( $regions );

$fire = new TFire();
$firesByRegion = $fire->getSortedByRegion();
$treeByRegion = array();

$node     = null;
$children = null;
$prevReg  = '';
$mapId    = '';

foreach( $firesByRegion as $eventId => $event )
{
    $regionId = $event[ 'region_id' ];
    
    if ( $children !== null )
    {
        $info  = array( 'type' => 'date', 'eventId' => $eventId, 'mapId' => $mapId );
        $child = array( 'text' => $event[ 'event_date' ], 'leaf' => true, 'info' => $info );
        $children[] = $child;
    }

    if ( $prevReg == $regionId )
    {
        continue;
    }
    
    if ( $node !== null )
    {
        $node[ 'children' ] = $children;
        $treeByRegion[] = $node;
    }
    
    $prevReg = $regionId;
    if ( empty( $regions[ $regionId ][ 'map_code' ] ) )
    {
        $node     = null;
        $children = null;
        
        continue;
    }
    
    $regionName = $event[ 'regionName' ];
    $mapId    = $regions[ $regionId ][ 'map_code' ];
    $info     = array( 'type' => 'region', 'eventId' => $eventId, 'mapId' => $mapId );
    $node     = array( 'text' => $regionName, 'leaf' => false, 'info' => $info, 'id' => $mapId );
    $children = array();
    
}

if ( !empty( $node ) )
{
    $node[ 'children' ] = $children;
    $treeByRegion[] = $node;
}

//header( 'Content-type: text/plain; charset='.TOptions::serverCharset );
$jsonTree = trans::phpValue2js( $treeByRegion );

$fp = fopen( TOptions::tmpFile( TOptions::treeByRegionFile ), "wb" );
fwrite( $fp, $jsonTree );
fclose( $fp );

/*$firesByDate = $fire->getAllFires( 'event_date' );
$nodesByDate = array();*/

?>